#!/usr/bin/env python3
"""
Properties文件语法高亮器
支持.properties配置文件的高亮显示
"""

from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QColor

class PropertiesHighlighter(QSyntaxHighlighter):
    """Properties文件语法高亮器"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.highlighting_rules = []
        
        # 键格式
        key_format = QTextCharFormat()
        key_format.setForeground(QColor(0, 0, 255))  # 蓝色
        key_format.setFontWeight(75)
        
        # 值格式
        value_format = QTextCharFormat()
        value_format.setForeground(QColor(163, 21, 21))  # 深红色
        
        # 注释格式
        comment_format = QTextCharFormat()
        comment_format.setForeground(QColor(0, 128, 0))  # 绿色
        comment_format.setFontItalic(True)
        
        # 分隔符格式
        separator_format = QTextCharFormat()
        separator_format.setForeground(QColor(128, 128, 0))  # 橄榄色
        separator_format.setFontWeight(75)
        
        # 特殊字符格式
        special_format = QTextCharFormat()
        special_format.setForeground(QColor(128, 0, 128))  # 紫色
        
        # 添加规则
        
        # 注释
        rule = (QRegExp(r'^[!#].*'), comment_format)
        self.highlighting_rules.append(rule)
        
        # 键（等号或冒号前的内容）
        rule = (QRegExp(r'^\s*[^=:]+?(?=\s*[=:])'), key_format)
        self.highlighting_rules.append(rule)
        
        # 分隔符
        rule = (QRegExp(r'[=:]'), separator_format)
        self.highlighting_rules.append(rule)
        
        # 值（分隔符后的内容）
        rule = (QRegExp(r'[=:]\s*[^\n\r]*'), value_format)
        self.highlighting_rules.append(rule)
        
        # 转义字符
        rule = (QRegExp(r'\\[tnr\\"\'\s]'), special_format)
        self.highlighting_rules.append(rule)
        
        # Unicode转义
        rule = (QRegExp(r'\\u[0-9a-fA-F]{4}'), special_format)
        self.highlighting_rules.append(rule)
        
        # 路径分隔符
        rule = (QRegExp(r'[/\\]'), special_format)
        self.highlighting_rules.append(rule)
        
        # 布尔值
        rule = (QRegExp(r'\b(true|false|yes|no|on|off)\b'), value_format)
        self.highlighting_rules.append(rule)
        
        # 数字
        rule = (QRegExp(r'\b\d+\.?\d*\b'), value_format)
        self.highlighting_rules.append(rule)
    
    def highlightBlock(self, text):
        """高亮文本块"""
        # 应用单行规则
        for pattern, format in self.highlighting_rules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)